package com.polaris.live.viewmodel.home

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.request
import com.polaris.live.common.network.state.ResultState
import com.polaris.live.common.network.state.paresException
import com.polaris.live.common.network.state.paresResult
import com.polaris.live.constant.UserConst
import com.polaris.live.net.homeService
import com.polaris.live.resp.back_resp.MatchHeartbeatResp
import com.polaris.live.resp.back_resp.MatchStartResp
import com.polaris.live.resp.go_resp.EndMatchBean
import com.polaris.live.resp.go_resp.MatchIdBean
import com.polaris.live.resp.go_resp.MatchStartBean
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * MatchViewModel
 *
 * @author Created by 半仙 on 2023/10/20/020 15:01
 */
class MatchViewModel : BaseViewModel() {

    /**
     * 匹配中动效
     */
    val matchAnimaLiveData = MutableLiveData<ResultState<List<String>>>()
    fun matchAnimation() {
        request({ homeService.matchAnimation() }, matchAnimaLiveData)
    }

    /**
     * 结束匹配
     */
    fun endMatch(matchId: Long, endType: Int) {
        val body = EndMatchBean(matchId, endType)
        request({ homeService.endMatch(body) }, {})
    }

    /**
     * 匹配心跳
     */
    val matchLiveData = MutableLiveData<ResultState<MatchHeartbeatResp>>()
    fun matchHeartbeat(matchId: Long) {
        request({ homeService.matchHeartbeat(MatchIdBean(matchId)) }, matchLiveData)
    }

    val matchNextLiveData = MutableLiveData<Long>()
    private var callHeartbeatJob: Job? = null
    fun launchCallHeartbeat(matchId: Long) {
        callHeartbeatJob = viewModelScope.launch {
            try {
                matchHeartbeat(matchId)
                delay(5000)

                matchNextLiveData.value = matchId
            } finally {
                if (callHeartbeatJob == coroutineContext[Job]) {
                    callHeartbeatJob = null
                }
            }
        }
    }

    /**
     * 重试匹配
     */
    val rematchLiveData = MutableLiveData<ResultState<MatchStartResp>>()
    fun rematch() {
        callHeartbeatJob?.cancel()

        request({ homeService.matchStart(MatchStartBean(CommonConst.MatchStart.MANUAL, UserConst.From.MATCH)) }, {
            rematchLiveData.paresResult(it)

            launchCallHeartbeat(it.id)
        }, {
            rematchLiveData.paresException(it)
        })
    }

    override fun onCleared() {
        super.onCleared()
        callHeartbeatJob?.cancel()
        callHeartbeatJob = null
    }
}